package descentFly.app.tools
{
	import UIFree.controls.uif_arrowbutton;
	import UIFree.controls.uif_button;
	import UIFree.uif_component;
	import UIFree.uif_draw;
	import UIFree.uif_ecomponent;
	
	import descentFly.app.df_component;
	import descentFly.chips.df_chip;
	import descentFly.chips.df_weapont;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	
	public class df_weapontPanel extends df_chipTool {
		
		public static const BUTTONWIDTH: int = 12;
		private var _weapont: df_weapont;
		private var _arrows: Array;
		
		public function df_weapontPanel(parent:uif_component, aheight:int=0) {
			super(parent, 180, aheight);
		}
		
		override protected function createComponents(layer: df_component, inner: Rectangle):void {
			super.createComponents(layer, inner);
			label.x 	+= BUTTONWIDTH;
			label.width -= BUTTONWIDTH * 2;
			
			_arrows = [
				new uif_arrowbutton(layer, inner.x, inner.y, BUTTONWIDTH, BUTTONWIDTH * 1.5, uif_draw.LEFT, 'arrow'),
				new uif_arrowbutton(layer, inner.x + inner.width - BUTTONWIDTH, inner.y, BUTTONWIDTH, BUTTONWIDTH * 1.5, uif_draw.RIGHT, 'arrow')
			]
			_arrows[0].addEvent(MouseEvent.CLICK, doLeft); 
			_arrows[1].addEvent(MouseEvent.CLICK, doRight);
			refreshVisibilityArrows();
		}
		
		protected function refreshVisibilityArrows(): void {
			var vis: Boolean = myChip && (myChip.nextWeapont != myChip.weapontIndex)
			_arrows[0].slideVisible(vis);
			_arrows[1].slideVisible(vis);
		}
		
		protected function doLeft(e: Event): void {
			myChip.weapontIndex = myChip.prevWeapont;
		}
		
		protected function doRight(e: Event): void {
			myChip.weapontIndex = myChip.nextWeapont;	
		}
		
		override protected function setMyChip(a_chip: df_chip):void {
			if (myChip) myChip.removeEventListener(df_chip.CHANGEWEAPONT, doChangeWeapont);
			super.setMyChip(a_chip);
			if (myChip) myChip.addEventListener(df_chip.CHANGEWEAPONT, doChangeWeapont);
//			refreshWeapont();
		}
		
		protected function doChangeWeapont(e: Event): void {
			refreshWeapont();
		}
		
		protected function doChangeAmmo(e: Event): void {
			refreshAmmo();
		}
		
		protected function refreshAmmo(): void {
			if (_weapont) {
				label.text = _weapont.options.name;
				if ((pb.visible = _weapont.limited) == true) {
					pb.percent = _weapont.ammo/_weapont.ammoLimit;
					label.text += ' ' + Math.round(pb.percent * 100) + '%';
				}
			} else {
				pb.visible = false;
				label.text = '';
			}
		}
		
		protected function refreshWeapont(): void {
			if (_weapont) _weapont.removeEventListener(df_weapont.CHANGE_AMMO, doChangeAmmo);
			
			if (myChip) {
				_weapont = myChip.currentWeapont;
				_weapont.addEventListener(df_weapont.CHANGE_AMMO, doChangeAmmo);
			} else {
				pb.percent 	= 0;
				_weapont	= null;
			}
			refreshAmmo();
			refreshVisibilityArrows();
		}
	}
}